﻿# ------------------------------ #
# Workflow Manager Configuration #
# ------------------------------ #
param([string]$virtualMachineService, [string]$virtualMachineName)

Write-Information "Virtual machine '$virtualMachineName' Workflow Manager '$($script.type)' configuration ... " -NoNewLine $true
$userName = $subscription.virtualMachines.adminUserName
$password = $subscription.virtualMachines.password
$netBiosDomain = $subscription.virtualMachines.netBiosDomain
$uri = Get-AzureWinRMUri -ServiceName $virtualMachineService -Name $virtualMachineName
$credential = New-Object System.Management.Automation.PSCredential(($netBiosDomain + "\" + $userName), (ConvertTo-SecureString $password -AsPlainText -Force))
$session = New-PSSession -ComputerName $uri[0].DnsSafeHost -Credential $credential -Port (Get-VirtualMachineInstanceEndpointPort $subscription $virtualMachineName) -UseSSL -Authentication Credssp
switch ($script.type)
{
	"Prepare"
	{
		Invoke-Command -Session $session -ScriptBlock {
			Import-Module ServerManager
			$result = Add-WindowsFeature Net-Framework-Features -Source W:\sources\sxs -WarningAction Ignore
			if (!$? -or $result.Success -eq $false) { throw ".NET Framework 3.5 deployment failed." }
		}
	}
	"Install"
	{
		Invoke-Command -Session $session -ScriptBlock {
			if ((Start-Process -FilePath "M:\bin\WebpiCmd.exe" -ArgumentList "/Install /Products:ServiceBus /AcceptEULA /SuppressReboot /SuppressPostFinish /XML:M:\feeds\latest\webproductlist.xml" -Wait -PassThru).ExitCode -ne 0)
            {
                throw "ServiceBus 1.0 installation failed. Check '$Env:LOCALAPPDATA\Microsoft\Web Platform Installer\Logs' for more details."
            }
			if ((Start-Process -FilePath "M:\updates\ServiceBus-KB2799752-x64-EN.exe" -ArgumentList "/passive /norestart /quiet /log ServiceBus-KB2799752-x64-EN.log" -Wait -PassThru).ExitCode -ne 0)
            {
                throw "ServiceBus 1.0 CU1 (KB2799752) installation failed. Check 'ServiceBus-KB2799752-x64-EN.log' for more details."
            }
			if ((Start-Process -FilePath "M:\bin\WebpiCmd.exe" -ArgumentList "/Install /Products:WorkflowManagerRefresh /AcceptEULA /SuppressReboot /SuppressPostFinish /XML:M:\feeds\latest\webproductlist.xml" -Wait -PassThru).ExitCode -ne 0)
            {
                throw "Workflow Manager 1.0 Refresh installation failed. Check '$Env:LOCALAPPDATA\Microsoft\Web Platform Installer\Logs' for more details."
            }
		}
	}
	"Client"
	{
		Invoke-Command -Session $session -ScriptBlock {
			if ((Start-Process -FilePath "M:\bin\WebpiCmd.exe" -ArgumentList "/Install /Products:WorkflowClient /AcceptEULA /SuppressReboot /XML:M:\feeds\latest\webproductlist.xml" -Wait -PassThru).ExitCode -ne 0)
            {
                throw "Workflow Client installation failed. Check '$Env:LOCALAPPDATA\Microsoft\Web Platform Installer\Logs' for more details."
            }
		}
	}
	"Create"
	{
		Invoke-Command -Session $session -ScriptBlock {
			param([string]$farmDns, [string]$userName, [string]$password, [string]$adminGroup, [string]$certificateName, [string]$sbDatabaseServer, [string]$sbManagementDatabase, [string]$sbGatewayDatabase, [string]$sbMessageContainerDatabase, [string]$wfDatabaseServer, [string]$wfManagementDatabase, [string]$wfInstanceDatabase, [string]$wfResourceDatabase)
			Import-Module ServiceBus
			Import-Module WorkflowManager
			$securePassword = ConvertTo-SecureString -AsPlainText -Force -String $password;
            $thumbprint = (Get-Item Cert:\LocalMachine\My\* | ? {$_.FriendlyName -eq $certificateName}).Thumbprint
			# Create new SB Farm
			$result = New-SBFarm -RunAsAccount $userName -AdminGroup $adminGroup -InternalPortRangeStart 9000 -TcpPort 9354 -MessageBrokerPort 9356 -FarmCertificateThumbprint $thumbprint -EncryptionCertificateThumbprint $thumbprint -SBFarmDBConnectionString "Data Source=$sbDatabaseServer;Initial Catalog=$sbManagementDatabase;Integrated Security=True;Encrypt=False" -GatewayDBConnectionString "Data Source=$sbDatabaseServer;Initial Catalog=$sbGatewayDatabase;Integrated Security=True;Encrypt=False" -MessageContainerDBConnectionString "Data Source=$sbDatabaseServer;Initial Catalog=$sbMessageContainerDatabase;Integrated Security=True;Encrypt=False";
			# Create new WF Farm
			$result = New-WFFarm -RunAsAccount $userName -AdminGroup $adminGroup -HttpsPort 12290 -HttpPort 12291 -OutboundCertificateThumbprint $thumbprint -SslCertificateThumbprint $thumbprint -EncryptionCertificateThumbprint $thumbprint -WFFarmDBConnectionString "Data Source=$wfDatabaseServer;Initial Catalog=$wfManagementDatabase;Integrated Security=True;Encrypt=False" -InstanceDBConnectionString "Data Source=$wfDatabaseServer;Initial Catalog=$wfInstanceDatabase;Integrated Security=True;Encrypt=False" -ResourceDBConnectionString "Data Source=$wfDatabaseServer;Initial Catalog=$wfResourceDatabase;Integrated Security=True;Encrypt=False";
			# Add SB Host
			$result = Add-SBHost -SBFarmDBConnectionString "Data Source=$sbDatabaseServer;Initial Catalog=$sbManagementDatabase;Integrated Security=True;Encrypt=False" -RunAsPassword $securePassword -EnableFirewallRules $true -ExternalBrokerUrl "sb://$farmDns";
			# Create new SB Namespace
			$result = New-SBNamespace -Name "WorkflowDefaultNamespace" -AddressingScheme "Path" -ManageUsers $userName,$([System.Security.Principal.WindowsIdentity]::GetCurrent().Name);
			Start-Sleep -Seconds 5
			# Add WF Host
            $clientConfiguration = Get-SBClientConfiguration -Namespaces "WorkflowDefaultNamespace"
            #$clientConfiguration = "Endpoint=sb://$farmDns/WorkflowDefaultNamespace;StsEndpoint=https://$($farmDns):9355/WorkflowDefaultNamespace;RuntimePort=9354;ManagementPort=9355";
			$result = Add-WFHost -WFFarmDBConnectionString "Data Source=$wfDatabaseServer;Initial Catalog=$wfManagementDatabase;Integrated Security=True;Encrypt=False" -RunAsPassword $securePassword -EnableFirewallRules $true -SBClientConfiguration $clientConfiguration;
			# Verify farm at: https://<farmDns>:12290; https://<farmDns>:12290/<scope>; Get-SBFarmStatus; Get-WFFarmStatus
		} -ArgumentList $script.farm, $script.userName, $script.password, $script.adminGroup, $script.certificateName, $script.serviceBus.databaseServer, $script.serviceBus.managementDatabase, $script.serviceBus.gatewayDatabase, $script.serviceBus.messageContainerDatabase, $script.workflowManager.databaseServer, $script.workflowManager.managementDatabase, $script.workflowManager.instanceDatabase, $script.workflowManager.resourceDatabase
	}
	"Join"
	{
		Invoke-Command -Session $session -ScriptBlock {
			param([string]$farmDns, [string]$password, [string]$sbDatabaseServer, [string]$sbManagementDatabase, [string]$wfDatabaseServer, [string]$wfManagementDatabase)
			Import-Module ServiceBus
			Import-Module WorkflowManager
			$securePassword = ConvertTo-SecureString -AsPlainText -Force -String $password;
			# Add SB Host
			$result = Add-SBHost -SBFarmDBConnectionString "Data Source=$sbDatabaseServer;Initial Catalog=$sbManagementDatabase;Integrated Security=True;Encrypt=False" -RunAsPassword $securePassword -EnableFirewallRules $true -ExternalBrokerUrl "sb://$farmDns";
			# Add WF Host
			$clientConfiguration = Get-SBClientConfiguration -Namespaces "WorkflowDefaultNamespace";
            #$clientConfiguration = "Endpoint=sb://$farmDns/WorkflowDefaultNamespace;StsEndpoint=https://$($farmDns):9355/WorkflowDefaultNamespace;RuntimePort=9354;ManagementPort=9355";
			$result = Add-WFHost -WFFarmDBConnectionString "Data Source=$wfDatabaseServer;Initial Catalog=$wfManagementDatabase;Integrated Security=True;Encrypt=False" -RunAsPassword $securePassword -EnableFirewallRules $true -SBClientConfiguration $clientConfiguration;
			# Verify farm at: https://<server>.bytezoo.net:12290; https://<server>.bytezoo.net:12290/<scope>; Get-SBFarmStatus; Get-WFFarmStatus;
		} -ArgumentList $script.farm, $script.password, $script.serviceBus.databaseServer, $script.serviceBus.managementDatabase, $script.workflowManager.databaseServer, $script.workflowManager.managementDatabase
	}
	"Connect"
	{
		Invoke-Command -Session $session -ScriptBlock {
			param([string]$site, [string]$workflowHost, [string]$scopeName)
			Add-PSSnapin Microsoft.SharePoint.PowerShell
			# Connect to Workflow Manager farm (Service Bus 1.0 CU2, Workflow Manager 1.0 CU2, Workflow Manager Client 1.0 CU2 are required for Windows Server 2012 R2)
			Register-SPWorkflowService -SPSite $site -WorkflowHostUri $workflowHost –AllowOAuthHttp -ScopeName $scopeName -Force
            # The is required to enable Workflow Apps after March PU
            $wms = Get-SPWorkflowServiceApplicationProxy
            $wms.RegisterWorkflowLifecycleManagementEnvironment()
			# Verify connection: Get-SPWorkflowServiceApplicationProxy | Format-List *; $p = Get-SPWorkflowServiceApplicationProxy; $s = Get-SPSite <site>; $p.GetWorkflowScopeName($s); $p.GetWorkflowServiceScopeInfo($s); $p.GetWorkflowServiceAddress($s); 
		} -ArgumentList $script.site, $script.workflowHost, $script.scopeName
	}
	default
	{
		throw "Workflow Manager type '$($script.type)' is not supported."
	}
}
Remove-PSSession $session
Write-Text "done."